<script setup>
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { CaretBottom, CaretTop } from "@element-plus/icons-vue";

import { getClients, getClientDetail, removeClient } from "@/api/client";
import ClientDetail from "./components/ClientDetail.vue";
import NothingPage from "@/assets/imgs/nothing.png";


const editableTab = ref()
const editableTabName = ref()
const detailVisible = ref(false)

const clients = ref([])

function toGetClients() {
  getClients().then(res => {
    if (res.code === 200) {
      clients.value = res.data
      if (!res.data || res.data.length <= 0) return
      const names = res.data.map(d => d.name)
      editableTab.value = null
      editableTabName.value = null
      if (names.length > 0) {
        editableTab.value = clients.value[0]
        editableTabName.value = clients.value[0].name
      }
      if (clients.value[0].willTopic) {
        readMqttWill.value = true
      }
    } else {
      ElMessage.error(res.msg)
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error("网络异常，请稍后重试")
  })
}
toGetClients()

function handleTabAdd() {
  detailVisible.value = true
  editClientData.value = null
}

function handleTabRemove(tabName) {
  console.log(tabName);
  ElMessageBox.confirm(`确认要删除${tabName}吗？`, "警告", {
    type: 'warning',
    confirmButtonText: "确定",
    cancelButtonText: "取消"
  }).then(() => {
    removeClient(tabName).then(res => {
      if (res.code === 200) {
        ElMessage.success("删除成功")
        toGetClients()
      } else {
        ElMessage.error(res.msg)
      }
    }).catch(err => {
      console.log(err)
      ElMessage.error("网络异常，请稍后重试")
    })
  }).catch(() => {})
}

const readMqttWill = ref(false)

const editClientData = ref()

function toEditClient(name) {
  getClientDetail(name).then(res => {
    if (res.code === 200) {
      detailVisible.value = true
      editClientData.value = res.data
    } else {
      ElMessage.error(res.msg)
    }
  }).catch(err => {
    console.log(err)
    ElMessage.error("网络异常，请稍后重试")
  })
}
</script>

<template>
	<el-tabs 
    type="card" v-model="editableTabName" 
    closable @tab-remove="handleTabRemove"
    addable @tab-add="handleTabAdd"
  >
    <el-tab-pane v-for="client in clients" :label="`(${client.type})${client.name}`" :name="client.name">
      <div v-if="client.type === 'MQTT'">
        <el-descriptions
          border
          :column="1"
        >
          <el-descriptions-item label="客户端ID">{{ client.clientId }}</el-descriptions-item>
          <el-descriptions-item label="服务器地址">{{ client.comType }} : // {{ client.host }} : {{ client.port }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ client.username }}</el-descriptions-item>
          <el-descriptions-item label="密码">{{ client.password }}</el-descriptions-item>
        </el-descriptions>
        <div v-if="editableTab.willTopic">
          <el-button 
            link :icon="readMqttWill ? CaretTop : CaretBottom" 
            style="margin: 16px 0 8px 0;"
            @click="readMqttWill = !readMqttWill"
          >遗嘱配置</el-button>
          <Transition name="will">
            <el-descriptions border :column="1" class="will-set" v-show="readMqttWill">
              <el-descriptions-item label-align="left" label="遗嘱话题">{{ client.willTopic }}</el-descriptions-item>
              <el-descriptions-item label-align="left" label="遗嘱消息">{{ client.willPayload }}</el-descriptions-item>
              <el-descriptions-item label-align="left" label="遗嘱QoS">{{ client.willQoS }}</el-descriptions-item>
              <el-descriptions-item label-align="left" label="遗嘱持久化">{{ client.willRetain? '✔️' : '❌' }}</el-descriptions-item>
            </el-descriptions>
          </Transition>
        </div>
      </div>
      <el-button class="edit-btn" type="primary" @click="toEditClient(client.name)">修 改</el-button>
    </el-tab-pane>
  </el-tabs>
  <el-empty v-if="!clients.length || clients.length <= 0" :image="NothingPage">
      <template #description>
        查无客户端信息，你可以先
        <el-button link type="primary" @click="handleTabAdd">点击此处</el-button>
        或右上角创建客户端
      </template>
    </el-empty>
  <client-detail v-model:visible="detailVisible" :data="editClientData" @submit="toGetClients()" />
</template>

<style scoped lang="scss">
// :deep(.el-descriptions__cell) {
//   width: 0px;
// }
:deep(.el-descriptions__body) {
  width: 100%;
  .el-descriptions__cell {
    width: 0;
  }
}
:deep(.server-ip) {
	.el-input-group__append {
		padding: 0;
	}
	.ip-separator {
		font-size: 16px;
		margin: 0 8px;
	}
}
.will-set {
  height: 300px;
}
.will-enter-active, .will-leave-active {
  transition: all .2s ease;
  overflow: hidden;
}
.will-enter-from, .will-leave-to {
  height: 0 !important;
  opacity: 0;
}
.edit-btn {
  margin-top: 24px;
}
</style>